﻿
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using YanhuaMMO;
using UnityEngine.UI;
using DG.Tweening;

public class GameLoginBefore : Base , IView
{
    public static GameLoginBefore Instance;
    
    // step1 logo
    public GameObject logoGo = null;
    public Text tipsTxt = null;
    public Image tipsImg = null;
    public Image tipsBgWhiteImg = null;
    public GameObject tipsCavas = null;
    //public float logoDelayTime = 3;

    // step2 update
    public GameObject updateManager = null;
    private GameObject updateGo = null;
    private GameObject updateComfirnGo = null;
    private GameObject updateComfirnKB = null;
    private List<string> updateFiles = null;
    private List<string> changePackageMsg = null;

    private bool isWhiteToBlack = false;
    float whiteChangeTime = 0;
    public float whiteChangePara = 2f;//90/30 = 3s

    private bool logoWait = false;
	private Transform videoPlayer;
	private Transform mediaPlayer;

	float clickTime = 0;
    int dotCount = 0;
    float alphaChangeTime = 0;
    public float alphaChangePara = 0.35f;//90/30 = 3s
    List<string> MessageList
    {
        get
        {
            return new List<string>()
            {
                NotiConst.UPDATE_START,
                NotiConst.UPDATE_FINISH,
                NotiConst.UPDATE_LOGIN,
                NotiConst.CHANGE_PACKAGE,
				NotiConst.DOWNLOAD_FILE_FAILED,
            };
        }
    }

    // step3 login
    public List<GameObject> loginGos = new List<GameObject>();

    private void Awake()
    {
        tipsCavas.SetActive(false);
        Instance = this;
        RemoveMessage(this, MessageList);
        RegisterMessage(this, MessageList);
    }

    private void Start()
    {
		var canvas = GameObject.Find("Canvas");
		videoPlayer = canvas.transform.Find("DisplayUGUI");
		mediaPlayer = canvas.transform.Find("MediaPlayer_logo");
        //Debug.Log(">>>>>>>更新进");
#if UNITY_EDITOR && !CLIENT_BUNDLE
		StepLogin();
		//StartCoroutine(StepLOGO());
#else
        StartCoroutine(StepLOGO());
        //StepUpdate();// TODO 测试版本临时处理, 打开LOGO这一句要屏蔽
#endif
	}
    private void Update()
    {
        if (isWhiteToBlack)
        {
            if (tipsBgWhiteImg.color.r > 0)
            {
                float red = 1 - (Time.realtimeSinceStartup - whiteChangeTime) * whiteChangePara;

                red = red > 0 ? red : 0;
                Debug.LogError(red);
                tipsBgWhiteImg.color = new Color(red, red, red, 1);
                //Debug.LogError(tipsImg.color.a);
            }
        }
        if (logoWait)
        {
            if (tipsBgWhiteImg.color.r > 0)
            {
                tipsBgWhiteImg.color = new Color(0, 0, 0, 1);
            }
            if (tipsImg.color.a < 1)
            {
                float alpha =    (Time.realtimeSinceStartup - alphaChangeTime)/ alphaChangePara;
               
                alpha = alpha < 1 ? alpha : 1;
                //Debug.LogError(alpha);
                tipsImg.color = new Color(tipsImg.color.r, tipsImg.color.g, tipsImg.color.b, alpha < 1 ? alpha: 1);
                tipsTxt.color = new Color(tipsTxt.color.r, tipsTxt.color.g, tipsTxt.color.b, alpha < 1 ? alpha : 1);
                //Debug.LogError(tipsImg.color.a);
            }
   
            if(Time.realtimeSinceStartup - clickTime > 0.8)
            {
                clickTime = Time.realtimeSinceStartup;
                dotCount = dotCount % 4;
                //Debug.Log("显示出来了======dotCount" + dotCount);
                if (dotCount == 0)
                {
                    tipsTxt.text = "正在进入奥米勒斯大陆";
                }
                else if(dotCount == 1)
                {
                    tipsTxt.text = "正在进入奥米勒斯大陆.";
                }
                else if (dotCount == 2)
                {
                    tipsTxt.text = "正在进入奥米勒斯大陆..";
                }
                else if (dotCount == 3)
                {
                    tipsTxt.text = "正在进入奥米勒斯大陆...";
                }

                dotCount++;
            }
            
        }
    }
    /// <summary>
    /// 显示Logo
    /// </summary>
    /// <returns></returns>
    public IEnumerator StepLOGO() 
    {
        //QualitySettings.vSyncCount = 1;
        var videoCom = videoPlayer.GetComponent<AVProPlayerControl>();
		videoCom.FindMediaPlayerCompnent(mediaPlayer.transform, "avvideo/logoAV.mp4");
		videoCom.Rewind();
		yield return new WaitForSeconds(3.65f);
        isWhiteToBlack = true;
        tipsCavas.SetActive(true);
        whiteChangeTime = Time.realtimeSinceStartup;
        yield return new WaitForSeconds(1 / whiteChangePara);
        isWhiteToBlack = false;
        logoWait = true;
		tipsCavas.SetActive(true);
        alphaChangeTime = Time.realtimeSinceStartup;
        //Debug.Log("显示出来了======");
        yield return new WaitForSeconds(0.3f);
		StepUpdate();
		/*logoGo.SetActive(true);
		var image = logoGo.transform.Find("Image").gameObject;
		var av = logoGo.transform.Find("logoAV").gameObject;
		var camera = logoGo.transform.Find("GuiCamera (1)").gameObject;
		//image.SetActive(true);
		//av.SetActive(false);
		//camera.SetActive(false);
		//yield return new WaitForSeconds(1.5f);
		//image.GetComponent<Image>().DOFade(0,0.5f);
		//yield return new WaitForSeconds(0.5f);
		av.SetActive(true);
		camera.SetActive(true);
        image.SetActive(false);
        yield return new WaitForSeconds(logoDelayTime);
        logoWait = true;
        tipsCavas.SetActive(true);
        Debug.Log("显示出来了======");
        StepUpdate();*/
	}

    /// <summary>
    /// 检测下载 如果不需要下载直接进入登录界面
    /// </summary>
    private void StepUpdate()
    {
        //Debug.Log(">>>>>>>>StepUpdate");
        updateManager.SetActive(true);// 启动Tolua的下载流程
    }
    public void ClickStartUpdate() 
    {
        updateComfirnGo.SetActive(false);

        // 开始下载
        StartCoroutine(YanhuaMMO.LuaHelper.GetGameManager().OnUpdateResourceUpdate(updateFiles));
    }
    public void ClickCancelUpdate() 
    {
        TA.TABehavior.Track("cancel_hot_update");
        Application.Quit();
    }
    public void ClickCancelChangePackage()
    {
        TA.TABehavior.Track("cancel_Strong_update");
        Debug.Log("ClickCancelChangePackage===");
        Application.Quit();
    }
    public void ClickChangePackage()
    {
        TA.TABehavior.Track("start_Strong_update");
        Debug.Log("ClickChangePackage===" + changePackageMsg[1]);
        Application.OpenURL(changePackageMsg[1]);
    }
    /// <summary>
    /// 尝试更新
    /// </summary>
    /// <param name="isUpdate"></param>
    public void UpdateStepUpdateStart() 
    {
		// AppFacade.Instance.AddManager<ResourceManager>(ManagerName.Resource); 
		ResourceManager.GetResourceManager().LoadPrefab("Prefabs/Update/UpdateGame", asset =>
        {

			if (!asset) 
            {
                Debug.LogError("Prefabs/Update/UpdateGame is not find");
                return;
            }

            DelLogo();

            updateGo = GameObject.Instantiate(asset, GameObject.Find("Canvas").transform);
            updateGo.AddComponent<AppView>();
            LuaHelper.GetPanelManager().uiDownLoad = updateGo;
            updateGo.SetActive(true);
            updateGo.transform.parent = GameObject.Find("Canvas").transform;
            updateGo.transform.localPosition = GameObject.Find("GuiCamera").transform.localPosition;
            updateGo.transform.localScale = Vector3.one;
            updateComfirnGo = updateGo.transform.Find("UiConfirm").gameObject;
            //float comfirnGoScaleFactor = 1920.0f / Screen.height;
            //updateComfirnGo.transform.localScale = new Vector3(comfirnGoScaleFactor, comfirnGoScaleFactor, comfirnGoScaleFactor);
            updateGo.transform.Find("bottom/ShowText").GetComponent<Text>().text = "等待确认中";
            updateComfirnKB = updateComfirnGo.transform.Find("TextMB").gameObject;
			Transform pa = updateGo.transform.Find("BG/Bg1_PA");
			if (pa != null)
			{
				pa.gameObject.SetActive(AppConst.drawingState == 1);
			}
			else
			{
				Debug.LogError("找不到资源BG/Bg1_PA");
			}
            if (changePackageMsg != null)
            {
                updateComfirnGo.transform.Find("Button/ButtonCancel").GetComponent<Button>().onClick.AddListener(ClickCancelChangePackage);
                updateComfirnGo.transform.Find("Button/ButtonOk").GetComponent<Button>().onClick.AddListener(ClickChangePackage);
                updateComfirnGo.SetActive(true);
                Debug.Log("changePackageMsg===");
                updateComfirnKB.GetComponent<Text>().text = "（需要下载新的安装包：" + changePackageMsg[2] + "）";
            }
            else
            {
                // 不是wifi环境要提示是否更新
                if (Application.internetReachability != NetworkReachability.ReachableViaLocalAreaNetwork)
                {
                    updateComfirnGo.transform.Find("Button/ButtonCancel").GetComponent<Button>().onClick.AddListener(ClickCancelUpdate);
                    updateComfirnGo.transform.Find("Button/ButtonOk").GetComponent<Button>().onClick.AddListener(ClickStartUpdate);
                    updateComfirnGo.SetActive(true);
                    float totalSize = 0;
                    string ext = "MB";
                    for (int i = 0; i < updateFiles.Count; i++)
                    {
                        var keyValue = updateFiles[i].Split('|');
                        totalSize += float.Parse(keyValue[2]);
                    }
                    totalSize /= 1024;
                    updateComfirnKB.GetComponent<Text>().text = "（本次更新大小包体大小：" + totalSize.ToString("f2") + ext;
                }
                else
                {
                    ClickStartUpdate();
                }
            }
        });
    }
	public void ShowDownloadFileErrorView(object error)
	{
        if (updateGo == null)
        {
            ResourceManager.GetResourceManager().LoadPrefab("Prefabs/Update/UpdateGame", asset =>
            {
                if (!asset)
                {
                    Debug.LogError("Prefabs/Update/UpdateGame is not find");
                    return;
                }

                DelLogo();

                updateGo = GameObject.Instantiate(asset, GameObject.Find("Canvas").transform);
                updateGo.SetActive(true);
                updateGo.transform.parent = GameObject.Find("Canvas").transform;
                updateGo.transform.localPosition = GameObject.Find("GuiCamera").transform.localPosition;
                updateGo.transform.localScale = Vector3.one;
                updateComfirnGo = updateGo.transform.Find("UiConfirm").gameObject;
                //updateGo.transform.Find("bottom/Progress").gameObject.SetActive(false);
                UpdateFailedUIOperation(error);

            });
        }
        else
        {
            UpdateFailedUIOperation(error);
        }
	}
    void UpdateFailedUIOperation(object error)
    {
        updateComfirnKB = updateComfirnGo.transform.Find("TextMB").gameObject;
        if(error != null)
        {
            updateComfirnGo.transform.Find("Text").GetComponent<Text>().text = error.ToString();
        }
        else
        {
            updateComfirnGo.transform.Find("Text").GetComponent<Text>().text = "部分文件下载失败,请检查网络";
        }
       
        updateComfirnKB.SetActive(false);
        Transform pa = updateGo.transform.Find("BG/Bg1_PA");
        if (pa != null)
        {
            pa.gameObject.SetActive(AppConst.drawingState == 1);
        }
        pa.gameObject.SetActive(false);
        updateComfirnGo.transform.Find("Button/ButtonCancel").GetComponent<Button>().onClick.AddListener(ClickCancelUpdate);
        updateComfirnGo.transform.Find("Button/ButtonOk").GetComponent<Button>().onClick.AddListener(ClickCancelUpdate);
        updateComfirnGo.SetActive(true);
    }
	/// <summary>
	/// 进入登录
	/// </summary>
	public void StepLogin() 
    {

        for (int i = 0; i < loginGos.Count; i++)
        {
            loginGos[i].SetActive(true);
        }
        // DelStartGame();

        //热更结束
        TA.TABehavior.Track("finish_hot_update");

    }

    public void DelStartGame()
    {
        Instance = null;
        DelLogo();
        if (updateGo != null) Destroy(updateGo);
    }

    private void DelLogo() 
    {
        logoWait = false;
        if (logoGo != null) Destroy(logoGo);
        if (tipsCavas != null) Destroy(tipsCavas);
		if (videoPlayer != null) Destroy(videoPlayer.gameObject);
		if (mediaPlayer != null) Destroy(mediaPlayer.gameObject);

	}

    public void OnMessage(IMessage message)
    {
        if (Instance == null) return;

        switch (message.Name) 
        {
            case NotiConst.CHANGE_PACKAGE:
                changePackageMsg = message.Body as List<string>;
                UpdateStepUpdateStart();
                break;
            case NotiConst.UPDATE_START:
                updateFiles = message.Body as List<string>;
                UpdateStepUpdateStart();
                break;
            case NotiConst.UPDATE_FINISH:
            case NotiConst.UPDATE_LOGIN:
                StepLogin();
                break;
			case NotiConst.DOWNLOAD_FILE_FAILED:
                ShowDownloadFileErrorView(message.Body);
				break;
			default:
                break;
        }
    }
}